package com.hxzy.tms;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.Cookie;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.WebUtils;

import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
 * 引用的ActionSupport抽象类
 * @author team1
 *
 */
public abstract class ExtendsActionSupport extends ActionSupport {
	private Logger logger = LoggerFactory.getLogger(getClass());
	private static final long serialVersionUID = -2286084026906314976L;
	private String nextPage;
    private String nowPage;
	/**
	 * 保存会话
	 * @param key 键
	 * @param value 值
	 */
	protected void saveSession(String key, Object value) {
		ActionContext.getContext().getSession().put(key, value);
	}
	/**
	 * 通过键得到会话
	 * @param key 键
	 * @return Object对象
	 */
	protected Object getSession(String key) {
		return ActionContext.getContext().getSession().get(key);
	}
	/**
	 * 得到当前地址
	 * @return String类型
	 */
	protected String getAddr() {
		return ServletActionContext.getRequest().getRemoteAddr();
	}
	/**
	 * 检查当前提交方式是POST
	 * @return boolean类型
	 */
	protected boolean isPost() {
		return "POST".equals(ServletActionContext.getRequest().getMethod());
	}
	/**
	 * 检查当前提交方式是GET
	 * @return boolean类型
	 */
	protected boolean isGet() {
		return "GET".equals(ServletActionContext.getRequest().getMethod());
	}
	/**
	 * 向客户端写入数据方法
	 * @param entity 传入对象
	 */
	protected void writeJson(Object entity) {
		ServletActionContext.getResponse().setCharacterEncoding("utf-8");
		ServletActionContext.getResponse().setContentType("application/json");
		try {
			Gson gson = new Gson();
			ServletActionContext.getResponse().getWriter().println(gson.toJson(entity));
		} catch (IOException e) {
			logger.error("向客户端写入 json 字符串", e);
		}
	}
	/**
	 * 写入Cookie值
	 * @param cookie
	 */
	protected void addCookie(Cookie cookie) {
		ServletActionContext.getResponse().addCookie(cookie);
	}
	/**
	 * 获取Cookie值
	 * @param key 键
	 * @return String类型
	 */
	protected String getCookie(String key) {
		Cookie c = WebUtils.getCookie(ServletActionContext.getRequest(), key);
		return c != null ? c.getValue() : null;
	}
	public String getNextPage() {
      return nextPage;
  }
  protected void setNextPage(String nextPage) {
      this.nextPage = nextPage;
  }
  public String getNowPage() {
      return nowPage;
  }
  protected void setNowPage(String nowPage) {
      this.nowPage = nowPage;
      saveSession("nowPage", nowPage);
  }
  /**
   * 得到当前日期
   * @return
   */
  protected Date getTimeNow(){
      return Calendar.getInstance().getTime();
  }
}